const axios = require("axios");
const urlJoin = require("url-join");
const semver = require("semver");

/**
 * 获取npm源最新版本
 * @param baseVersion 当前版本号
 * @param npmName npm名称
 * @param registry 源
 * @returns {Promise<null|*>}
 */
async function getNpmSemverVersion(baseVersion, npmName, registry) {
  const versions = await getNpmVersions(npmName, registry);
  const newVersions = getSemverVersions(baseVersion, versions);
  if (newVersions && newVersions.length > 0) {
    return newVersions[0];
  }
  return null;
}
/**
 * 将大于baseVersions版本进行排序
 * @param {*} baseVersions 比较版本
 * @param {*} versions 版本列表
 * @returns
 */
function getSemverVersions(baseVersions, versions) {
  return versions
    .filter((version) => semver.satisfies(version, `>${baseVersions}`))
    .sort((a, b) => (semver.gt(b, a) ? 1 : -1));
}
/**
 * 获取最新版本
 * @param {string} packageName package名称
 */
async function getNpmLatestVersion(packageName, registry) {
  const versions = await getNpmVersions(packageName, registry);
  if (versions) {
    return versions.sort((a, b) => semver.gt(b, a))[0];
  }
  return null;
}
/**
 * 获取对应npmName的所有版本
 * @param npmName
 * @param registry
 * @returns {Promise<string[]>}
 */
async function getNpmVersions(npmName, registry) {
  const data = await getNpmInfo(npmName, registry);
  if (data) {
    return Object.keys(data.versions);
  } else {
    [];
  }
}

/**
 * 发送请求获取当前npmName的信息
 * @param npmName
 * @param registry
 * @returns {null|Promise<axios.AxiosResponse<any>>}
 */
function getNpmInfo(npmName, registry) {
  if (!npmName) {
    return null;
  }
  const registryUrl = registry || getDefaultRegistry(true);
  const npmNameUrl = urlJoin(registryUrl, npmName);
  return axios
    .get(npmNameUrl)
    .then((response) => {
      if (response.status === 200) {
        return response.data;
      }
      return null;
    })
    .catch((err) => {
      console.log(err);
      return Promise.reject(err);
    });
}

function getDefaultRegistry(isOriginal = false) {
  return isOriginal
    ? "https://registry.npmjs.org"
    : "https://registry.npm.taobao.org";
}

module.exports = {
  getNpmSemverVersion,
  getNpmLatestVersion,
  getDefaultRegistry,
};
